<?php

namespace App\Http\Controllers\Backstage\File;

use App\Models\UploadFile;
use App\Http\Controllers\Controller;
use Illuminate\Contracts\Cache\Repository;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
//后台上传文件模块
class FileController extends Controller
{
    //编辑器上传多文件
    public function editfileupload(Request $request)
    {
        $token = $request->input('token');
        //验证权限
        $verifytoken = verifyBackstageToken($token);
        if (is_array($verifytoken)) {
            return $verifytoken;
        }
        $file = $request->file("mypic");
        // dd($file);
        if (!empty($file)) {
            foreach ($file as $key => $value) {
                $len = $key;
            }
            if ($len > 25) {
                return response()->json(['ResultData' => 6, 'info' => '最多可以上传25张图片']);
            }
            $m = 0;
            $k = 0;
            for ($i = 0; $i <= $len; $i++) {
                // $n 表示第几张图片
                $n = $i + 1;
                if ($file[$i]->isValid()) {
                    if (in_array(strtolower($file[$i]->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {


                        $filename = $file[$i]->getClientOriginalName(); //获取上传原文件名
                        $ext = $file[$i]->getClientOriginalExtension(); //获取上传文件的后缀名
                        $filemd5 = md5_file($file[$i]); //md5散列
                        $filesha1 = sha1_file($file[$i]); //sha1散列
                        // 重命名
                        $filename = time() . Str::random(6) . "." . $ext;
                        //文件类型
                        $finfo = finfo_open(FILEINFO_MIME);
                        $mime_type = finfo_file($finfo, $file[$i]);
                        finfo_close($finfo);
                        $mime_type = str_replace(" charset=binary", "", $mime_type);
                        //文件大小
                        $filesize = filesize($file[$i]);
                        $map['file_md5'] = $filemd5;
                        $map['file_sha1'] = $filesha1;
                        $file_info = UploadFile::where($map)->first();
                        //判断文件库信息
                        if ($file_info) {
                            // $newFileName = $file_info->file_name;
                            $time = date('Y-m-d', $file_info->create_flie_time);
                            // $newFileName =  http_type() .  $_SERVER['HTTP_HOST']  . '/' . "uploads/images/".$time . '/' . $file_info->file_name;
                            $newFileName = http_type() .  $_SERVER['HTTP_HOST'] . '/' . $file_info->url . '/'  . $file_info->file_name;
                            $fileid = $file_info->fileid;
                            $m = $m + 1;
                        } else {
                            $time = date('Y-m-d', time());
                            $data['file_name'] = $filename;
                            $data['url'] = "uploads/images/" . $time;
                            $data['storage'] = 'localhost';
                            $data['file_md5'] = $filemd5;
                            $data['file_sha1'] = $filesha1;
                            $data['file_size'] = $filesize;
                            $data['file_type'] = $mime_type;
                            $data['extension'] = $ext;
                            $data['create_flie_time'] = time();
                            $info = UploadFile::insertGetId($data);
                            $fileid = $info;
                            if ($info) {
                                if ($file[$i]->move("uploads/images/" . $time, $filename)) {
                                    $newFileName =  http_type() .  $_SERVER['HTTP_HOST']  . '/' . "uploads/images/" . $time . '/' . $filename;
                                    $m = $m + 1;
                                } else {
                                    $k = $k + 1;
                                }
                            }
                        }
                        $return = ['code' => 1, 'data' => $newFileName, 'fileid' => $fileid];
                        // $picname = $file[$i]->getClientOriginalName(); //获取上传原文件名
                        // $ext = $file[$i]->getClientOriginalExtension(); //获取上传文件的后缀名
                        // // 重命名
                        // $filename = time() . Str::random(6) . "." . $ext;
                        // if ($file[$i]->move("uploads/images", $filename)) {
                        //     $newFileName = 'http://' . $_SERVER["HTTP_HOST"] . '/' . "uploads/images" . '/' . $filename;
                        //     $m = $m + 1;
                        //     // return response()->json(['ResultData' => 0, 'info' => '上传成功', 'newFileName' => $newFileName ]);

                        // } else {
                        //     $k = $k + 1;
                        //     // return response()->json(['ResultData' => 4, 'info' => '上传失败']);
                        // }
                        // $msg = $m . "张图片上传成功 " . $k . "张图片上传失败<br>";
                        // $return = ['errno' => 0, 'data' => $newFileName];
                    } else {
                        return response()->json(['ResultData' => 3, 'info' => '第' . $n . '张图片后缀名不合法!<br/>' . '只支持jpeg/jpg/png/gif格式']);
                    }
                } else {
                    return response()->json(['ResultData' => 1, 'info' => '第' . $n . '张图片超过最大限制!<br/>' . '图片最大支持2M']);
                }
            }
        } else {
            return response()->json(['ResultData' => 5, 'info' => '请选择文件']);
        }
        return $return;
    }
    //上传单文件
    public function uploadfile(Request $request)
    {
        $token = $request->input('token');
        //验证权限
        $verifytoken = verifyBackstageToken($token);
        if (is_array($verifytoken)) {
            return $verifytoken;
        }
        $file = $request->file("files");
        // dd($request);
        if (!empty($file)) {
            foreach ($file as $key => $value) {
                $len = $key;
            }
            for ($i = 0; $i <= $len; $i++) {
                // $n 表示第几张图片
                // $n = $i + 1;
                if ($file[$i]->isValid()) {
                    if (in_array(strtolower($file[$i]->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
                        $filename = $file[$i]->getClientOriginalName(); //获取上传原文件名
                        $ext = $file[$i]->getClientOriginalExtension(); //获取上传文件的后缀名
                        $filemd5 = md5_file($file[$i]); //md5散列
                        $filesha1 = sha1_file($file[$i]); //sha1散列
                        // 重命名
                        $filename = time() . Str::random(6) . "." . $ext;
                        //文件类型
                        $finfo = finfo_open(FILEINFO_MIME);
                        $mime_type = finfo_file($finfo, $file[$i]);
                        finfo_close($finfo);
                        $mime_type = str_replace(" charset=binary", "", $mime_type);
                        //文件大小
                        $filesize = filesize($file[$i]);
                        $map['file_md5'] = $filemd5;
                        $map['file_sha1'] = $filesha1;
                        $file_info = UploadFile::where($map)->first();
                        //判断文件库信息
                        if ($file_info) {
                            $newFileName = $file_info->file_name;
                            $fileid = $file_info->fileid;
                        } else {
                            $time = date('Y-m-d', time());
                            $data['file_name'] = $filename;
                            $data['url'] = "uploads/images/" . $time;
                            $data['storage'] = 'localhost';
                            $data['file_md5'] = $filemd5;
                            $data['file_sha1'] = $filesha1;
                            $data['file_size'] = $filesize;
                            $data['file_type'] = $mime_type;
                            $data['extension'] = $ext;
                            $data['create_flie_time'] = time();
                            $info = UploadFile::insertGetId($data);
                            $fileid = $info;
                            if ($info) {
                                if ($file[$i]->move("uploads/images/" . $time, $filename)) {
                                    $newFileName = $filename;
                                }
                            }
                        }
                        $return = ['code' => 1, 'data' => $newFileName, 'fileid' => $fileid];
                    } else {
                        return response()->json(['code' => 0, 'msg' => '图片后缀名不合法!<br/>' . '只支持jpeg/jpg/png/gif格式']);
                    }
                } else {
                    return response()->json(['code' => 0, 'msg' => '图片超过最大限制!<br/>' . '图片最大支持2M']);
                }
            }
        } else {
            return response()->json(['code' => 0, 'msg' => '请选择文件']);
        }
        return $return;
    }

    //获取文件列表
    public function getFileList(Request $request)
    {
        $token = $request->query('token');
        //验证权限
        $verifytoken = verifyBackstageToken($token);
        if (is_array($verifytoken)) {
            return $verifytoken;
        }
        //翻页
        $pagenNum = (int) $request->query('page');
        $pageSize = (int) $request->query('pageSize');
        if ($pageSize > 50) {
            return false;
        }
        $page = $pagenNum - 1;
        if ($page != 0) {
            $page = $pageSize * $page;
        }
        $count = UploadFile::count();
        $info = UploadFile::orderByDesc('create_flie_time')
            ->offset($page)
            ->limit($pageSize)
            ->get();
        if ($info) {
            $info = json_decode($info, true);
            foreach ($info as $key => $value) {
                $info[$key]['url'] = http_type() .  $_SERVER['HTTP_HOST'] . '/' . $value['url'] . '/'  . $value['file_name'];
                $info[$key]['create_flie_time'] = date('Y-m-d', $value['create_flie_time']);
            }
            $data = success();
            $data['data'] = $info;
        } else {
            $data = fail();
        }
        $data['count'] = $count;
        return $data;
    }
    //删除文件
    public function DelFile(Request $request){
        $token = $request->get('token');
        //验证权限
        $verifytoken = verifyBackstageToken($token);
        if (is_array($verifytoken)) {
            return $verifytoken;
        }
        $map['fileid']=(int)$request->get('fileid');
        $info=UploadFile::where($map)->first();
        if(unlink($info->url.'/'.$info->file_name)){
            $msg=UploadFile::where($map)->delete();
            if($msg){
                $data=success();
            }else{
                $data=fail();
            }
        }else{
            $data=fail();
        }
        return $data;
    }
}
